from configparser import ConfigParser
import os,pymysql
import traceback # 打印报错堆栈信息

class ConRead:
    def __init__(self,fileName): # 需要读取的配置文件
        self.file = fileName
        # 把路径处理一下
        config_path = os.path.split(os.path.realpath(__file__))[0] + os.sep + fileName
        self.config = ConfigParser()
        self.config.read(config_path)
    def get_database_info(self,value):
        return self.config.get("databases",value)

class DB:
    def __init__(self,env):
        config = ConRead('config.ini')
        self.username = config.get_database_info(env+"_username") # 返回的就是 base_username：value的值
        self.databases_name = config.get_database_info(env+"_databases_name") # 返回的就是 base_databases_name：value的值
        self.password = config.get_database_info(env+"_password") # 返回的就是 base_password：value的值
        self.host = config.get_database_info(env+"_host") # 返回的就是 base_host：value的值
    def connect(self):
        self.db = pymysql.connect(user=self.username,password=self.password,host=self.host,database=self.databases_name,cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.db.cursor() # 实例化游标对象
    def close(self):
        self.cursor.close()
        self.db.close()
    def search_one(self,sql):
        result = 0
        self.connect()
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchone()
            self.close()
            return result
        except:
            self.db.rollback() # 先去回滚
            traceback.print_exc() # 打印错误信息
            self.close()
            return result
    def search_all(self,sql):
        result = 0
        self.connect()
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchall()
            self.close()
            return result
        except:
            self.db.rollback() # 先去回滚
            traceback.print_exc() # 打印错误信息
            self.close()
            return result
    def __edit(self,sql):
        result = 0
        self.connect()
        try:
            self.cursor.execute(sql)
            self.db.commit()
            self.close()
            result = 1
            return result
        except:
            self.db.rollback()  # 先去回滚
            traceback.print_exc()  # 打印错误信息
            self.close()
            return result
    def update(self,sql):
        return self.__edit(sql)
    def delete(self,sql):
        return self.__edit(sql)
    def insert(self,sql):
        return self.__edit(sql)
# if __name__ == '__main__':
#     d_base = DB('base')
#     # print(d_base.username)
#     # print(d_base.databases_name)
#     # print(d_base.password)
#     # print(d_base.host)
#     # 先去测试一下能否连接
#     # d_base.connect()
#     # 测试查询所有
#     # print(d_base.search_all("select * from eb_user_group"))
#     # 测试新增
#     d_base.insert("insert into eb_user_group values(11,'测试一下你就知道')")
#     # 再去查询
#     print(d_base.search_all("select * from eb_user_group"))